package com.tbl.modules.wms.controller.instorage;

import com.alibaba.fastjson.JSON;
import com.tbl.common.utils.DateUtils;
import com.tbl.common.utils.PageTbl;
import com.tbl.common.utils.PageUtils;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.platform.constant.LogActionConstant;
import com.tbl.modules.platform.constant.MenuConstant;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.service.system.LogService;
import com.tbl.modules.platform.service.system.RoleService;
import com.tbl.modules.platform.util.DeriveExcel;
import com.tbl.modules.wms.constant.Constant;
import com.tbl.modules.wms.entity.instorage.InstorageDetail;
import com.tbl.modules.wms.service.instorage.InstorageDetailService;
import com.tbl.modules.wms.service.instorage.InstorageService;
import com.tbl.modules.wms.service.inventory.InventoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 入库管理--装包管理
 * @author 70486
 */
@Controller
@RequestMapping(value = "/confirmWarehouse")
public class PackingController extends AbstractController {

    /**
     * 入库管理-入库表
     */
    @Autowired
    private InstorageService instorageService;
    /**
     * 入库管理-入库明细
     */
    @Autowired
    private InstorageDetailService instorageDetailService;
    /**
     * 日志管理
     */
    @Autowired
    private LogService logService;
    /**
     * 角色管理
     */
    @Autowired
    private RoleService roleService;
    /**
     * 盘点计划服务类
     */
    @Autowired
    private InventoryService inventoryService;
    
    /**
     * 跳转到装包管理列表页
     * @return ModelAndView
     */
    @RequestMapping(value = "/toList")
    public ModelAndView toList() {
        ModelAndView mv = this.getModelAndView();
        mv.addObject("operationCode", roleService.selectOperationByRoleId(getSessionUser().getRoleId(), MenuConstant.confirmWarehouse));
        //okk
        mv.addObject("factoryList",inventoryService.getFactoryList(Arrays.asList(getSessionUser().getFactoryCode().split(","))));
        mv.setViewName("techbloom/instorage/confirmWarehouse/confirmWarehouse_list");
        return mv;
    }

    /**
     * 获取装包管理列表数据
     * @param queryJsonString 查询条件
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/list.do")
    @ResponseBody
    public Map<String, Object> list(String queryJsonString) {
        Map<String, Object> map = new HashMap<>(4);
        if (!StringUtils.isEmptyString(queryJsonString)) {
            map = JSON.parseObject(queryJsonString);
        }
        //okk
        map.put("org", Arrays.asList(getSessionUser().getFactoryCode().split(",")));
        PageTbl page = this.getPage();
        PageUtils utils = instorageService.getPackDetailPageList(page, map);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("rows", utils.getList());
        map.put("total", utils.getTotalPage() == 0 ? 1 : utils.getTotalPage());
        return map;
    }

    /**
     * 功能描述:装包管理----点击确认改变状态
     * 1.修改标签表数据状态为2    （1.未确认 2.已包装  3.入库中  4.入库完成  5.已退库）
     * 2.判断当前状态
     * @param ids 标签初始化主键
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/warehouseConfirm.do")
    @ResponseBody
    public Map<String, Object> warehouseConfirm(String ids) {
        Map<String, Object> map = new HashMap<>(2);
        List<InstorageDetail> lstInstorageDetail = instorageDetailService.selectBatchIds(Arrays.stream(ids.split(",")).map(Long::parseLong)
                .collect(Collectors.toList())).stream().filter(s -> s.getConfirmBy() == null).collect(Collectors.toList());
        lstInstorageDetail.forEach(instorageDetail -> {
            if (instorageDetail.getState()==1 || instorageDetail.getState()==5){
                instorageDetail.setState(2);
            }
            instorageDetail.setConfirmBy(getUserId());
        });

        if (lstInstorageDetail.size() > 0){
            instorageService.packDetailConfirm(lstInstorageDetail);
            map.put("state", Constant.INT_ZERO);
            map.put("msg", "已更新！");
        }else {
            map.put("state", Constant.INT_ONE);
            map.put("msg", "没有需要包装补入的货物！");
        }
        return map;
    }

    /**
     * 导出Excel
     * @param request
     * @param response
     */
    @RequestMapping(value = "/materialExcel", method = RequestMethod.POST)
    @ResponseBody
    public void materialExcel(HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> map = new HashMap<>(10);
        map.put("startTime", request.getParameter("queryStartTime"));
        map.put("endTime", request.getParameter("queryEndTime"));
        map.put("ids", StringUtils.stringToInt(request.getParameter("ids")));
        map.put("entityNo", request.getParameter("queryEntityNo"));
        map.put("qaCode", request.getParameter("queryQaCode"));
        map.put("factoryarea", request.getParameter("factoryarea"));
        map.put("mcode", request.getParameter("mcode"));
        map.put("orderno", request.getParameter("orderno"));
        map.put("batchno", request.getParameter("batchno"));
        //okk
        map.put("org", Arrays.asList(getSessionUser().getFactoryCode().split(",")));

        try {
            String sheetName = "包装登记" + "(" + DateUtils.getDay() + ")";
            response.setHeader("Content-Type", "application/force-download");
            response.setHeader("Content-Type", "application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(sheetName.getBytes("gbk"),
                    "ISO8859-1") + ".xls");

            Map<String, String> mapFields = new LinkedHashMap<>();
            String [] excelIndexArray = request.getParameter("queryExportExcelIndex").split(",");

            if (excelIndexArray.length==1&&"".equals(excelIndexArray[0])) {
                mapFields.put("stateCode", "状态");
                mapFields.put("qaCode", "质保单号");
                mapFields.put("batchNo", "批次号");
                mapFields.put("ordernum", "订单号");
                mapFields.put("orderline", "订单行号");
                mapFields.put("entityNo", "工单号");
                mapFields.put("name", "厂区");
                mapFields.put("materialCode", "物料编码");
                mapFields.put("materialName", "物料名称");
                mapFields.put("createtimeStr","初始化时间");
                mapFields.put("meter", "数量");
                mapFields.put("unit", "单位");
                mapFields.put("weight", "重量");
                mapFields.put("colour", "颜色");
                mapFields.put("segmentno", "段号");
                mapFields.put("dishnumber", "盘具编码");
                mapFields.put("model", "盘规格");
                mapFields.put("outerDiameter", "盘外径");
                mapFields.put("storagetypeStr", "货物类型");
            }else {
                for (String s : excelIndexArray) {
                    if ("2".equals(s)) {
                        mapFields.put("name", "厂区");
                    } else if ("3".equals(s)) {
                        mapFields.put("materialCode", "物料编码");
                    } else if ("4".equals(s)) {
                        mapFields.put("materialName", "物料名称");
                    } else if ("5".equals(s)) {
                        mapFields.put("qaCode", "质保单号");
                    } else if ("6".equals(s)) {
                        mapFields.put("entityNo", "工单号");
                    } else if ("7".equals(s)) {
                        mapFields.put("ordernum", "订单号");
                    } else if ("8".equals(s)) {
                        mapFields.put("orderline", "订单行号");
                    } else if ("9".equals(s)) {
                        mapFields.put("batchNo", "批次号");
                    } else if ("10".equals(s)) {
                        mapFields.put("drumType", "盘类型");
                    } else if ("11".equals(s)) {
                        mapFields.put("model", "盘具规格");
                    } else if ("12".equals(s)) {
                        mapFields.put("innerDiameter", "盘内径");
                    } else if ("13".equals(s)) {
                        mapFields.put("outerDiameter", "盘外径");
                    } else if ("14".equals(s)) {
                        mapFields.put("meter", "数量");
                    } else if ("15".equals(s)) {
                        mapFields.put("unit", "单位");
                    } else if ("16".equals(s)) {
                        mapFields.put("weight", "重量");
                    } else if ("17".equals(s)) {
                        mapFields.put("colour", "颜色");
                    } else if ("18".equals(s)) {
                        mapFields.put("segmentno", "段号");
                    } else if ("19".equals(s)) {
                        mapFields.put("dishcode", "盘号");
                    } else if ("20".equals(s)) {
                        mapFields.put("dishnumber", "盘具编码");
                    } else if ("21".equals(s)) {
                        mapFields.put("confirmTime", "包装时间");
                    } else if ("22".equals(s)) {
                        mapFields.put("stateCode", "状态");
                    }
                }
            }

            DeriveExcel.exportExcel(sheetName, instorageService.getDetailExcelList(map), mapFields, response, "");
            logService.logInsert("装包列表导出", LogActionConstant.USER_EXPORT, request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
